﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Net;
using System.IO;
using System.Collections.Specialized;

namespace SpyApp.Controllers
{
    public class PaypalController : Controller
    {
        //
        // GET: /Paypal/

        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult IPN()
        {
            #region khởi tạo debugger
            AppDomain.CurrentDomain.SetData("DataDirectory", Server.MapPath("~/Logs"));
            var log4NetPath = Server.MapPath("~/log4net.config");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4NetPath));
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(PaypalController).FullName);
            #endregion

            logger.Info("[ Bắt đầu giao dịch ]");

            #region Lấy thông tin trả về
            byte[] param = Request.BinaryRead(Request.ContentLength);
            string strRequest = System.Text.Encoding.ASCII.GetString(param);
            //string strRequest = "mc_gross=2.03&protection_eligibility=Eligible&address_status=confirmed&item_number1=&tax=0.00&item_number2="
            //    + "&payer_id=QKEMKKN7YECJC&address_street=1+Main+St&payment_date=04%3A57%3A40+Dec+20%2C+2014+PST"
            //    + "&payment_status=Completed&charset=windows-1252&address_zip=95131&mc_shipping=2.00&mc_handling=0.00"
            //    + "&first_name=Test&mc_fee=0.36&address_country_code=US&address_name=Test+Buyer&notify_version=3.8"
            //    + "&custom=&payer_status=verified&business=luunghiatran-facilitator%40gmail.com&address_country=United+States&num_cart_items=2"
            //    + "&mc_handling1=0.00&mc_handling2=0.00&address_city=San+Jose&verify_sign=AkumErbjZXKcB8oU9ki6BtkS1uU8AKAz93gKXbDTjsXBLZOaxnnHvXR-"
            //    + "&payer_email=luunghiatran-buyer%40gmail.com&mc_shipping1=1.00&mc_shipping2=1.00&tax1=0.00&tax2=0.00&txn_id=54792906HE699272W"
            //    + "&payment_type=instant&last_name=Buyer&address_state=CA&item_name1=My+Cart+Item+1"
            //    + "&receiver_email=luunghiatran-facilitator%40gmail.com&item_name2=My+Cart+Item+2&payment_fee=0.36&quantity1=2&quantity2=1"
            //    + "&receiver_id=K5ATXHJ5WH948&txn_type=cart&mc_gross_1=1.02&mc_currency=USD&mc_gross_2=1.01&residence_country=US&test_ipn=1"
            //    + "&transaction_subject=&payment_gross=2.03&ipn_track_id=1d20b21a4af68";
            string strResponse_copy = strRequest;  //Save a copy of the initial info sent by PayPal
            //logger.Info("strResponse: " + strResponse_copy);
            #endregion

            #region Lấy xác nhận từ paypal
            //Post back to either sandbox or live
            string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            //string strSandbox = "https://www.paypal.com/cgi-bin/webscr";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
            //Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
            //req.Proxy = proxy;
            #region Send the request to PayPal and get the response
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();
            StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();
            #endregion
            #endregion

            if (strResponse == "VERIFIED")
            {
                //check the payment_status is Completed
                //check that txn_id has not been previously processed
                //check that receiver_email is your Primary PayPal email
                //check that payment_amount/payment_currency are correct
                //process payment

                NameValueCollection valueCollection = HttpUtility.ParseQueryString(strResponse_copy);
                string payer_email = valueCollection["payer_email"];        //đúng email gởi
                string receiver_email = valueCollection["receiver_email"];  //đúng email nhận
                string payment_status = valueCollection["payment_status"]; //trạng thái giao dịch Completed
                string txn_id = valueCollection["txn_id"]; // mã giao dịch chưa tồn tại
                string mc_currency = valueCollection["mc_currency"]; // loại tiền tệ USD

                logger.Info("payer email: " + payer_email);
                logger.Info("receiver_email: " + receiver_email);
                logger.Info("payment_status: " + payment_status);
                logger.Info("txn_id: " + txn_id);
                logger.Info("mc_currency: " + mc_currency);

                // kiểm tra đúng item, giá trị, số lượng
                int num_items = SpyApp.Models.BaseCommon.ConvertUtils.ToInt32(valueCollection["num_cart_items"]);
                for (int i = 1; i <= num_items; i++)
                {
                    string item_name = valueCollection["item_name" + i];
                    int quantity = SpyApp.Models.BaseCommon.ConvertUtils.ToInt32(valueCollection["quantity" + i]);// số lượng

                    double mc_gross = SpyApp.Models.BaseCommon.ConvertUtils.toDouble(valueCollection["mc_gross_" + i]);// tổng giá
                    double mc_shipping = SpyApp.Models.BaseCommon.ConvertUtils.toDouble(valueCollection["mc_shipping" + i]); // tiền shipping
                    double mc_total_price = mc_gross - mc_shipping;

                    logger.Info("item_name: " + item_name);
                    logger.Info("quantity: " + quantity);
                    logger.Info("mc_gross: " + mc_gross);
                    logger.Info("mc_shipping: " + mc_shipping);
                    logger.Info("mc_total_price: " + mc_total_price);
                }


                //foreach (var key in valueCollection.AllKeys)
                //{
                //    logger.Info(String.Format("Key: {0}\t\t{1}", key, valueCollection[key]));
                //}
            }
            else if (strResponse == "INVALID")
            {
                //log for manual investigation
            }
            else
            {
                //log response/ipn data for manual investigation
            }
            return View();
        }
    }
}
